<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Exception;


class Carsource extends Base
{
	/**
	 * 车源管理--列表
	 */
	public function carsource(){
		if($this->request->isPost()){
			//是否推荐
			if(input("iscom") !== null){
				model("Carsource")->where("sid",input("id"))->update(['is_commend'=>input("iscom")]);
				return ;
			}
			//是否热门
			if(input("ishot") !== null){
				model("Carsource")->where("sid",input("id"))->update(['is_hot'=>input("ishot")]);
				return ;
			}
			//是否已卖
			if(input("issell") !== null){
				model("Carsource")->where("sid",input("id"))->update(['is_sell'=>input("issell")]);
				return ;
			}
			//是否展示
			if($this->request->isPost() && isset($_POST['lock'])){
				if(input('post.lock')==1){
					model("Carsource")->where('sid='.input('post.id'))->update(['is_show'=>0]);
				}else{
					model("Carsource")->where('sid='.input('post.id'))->update(['is_show'=>1]);
				};
				return $this->success('1');
			}
			
		}
		$condition=[];
		if(input('bname')){
			$condition[]=['br.bname','like',"%".input('bname')."%"];
		}
		if(input('oname')){
			$condition[]=['s.oname','like',"%".input('oname')."%"];
		}
		if(input('aname')){
			$condition[]=['a.name','like',"%".input('aname')."%"];
		}
		if(input('pname')){
			$condition[]=['b.name','like',"%".input('pname')."%"];
		}
		if(input('preprice')){
			$condition[]=['s.preprice','<=',input('preprice')];
		}
		$info = model("Carsource")
			->field("a.name as aname,b.name as pname,s.sid,t.tname,c.gname,c.name as cname,l.lname,s.licensetime,s.oname,s.click,s.pubtime,s.is_commend,s.is_hot,s.is_sell,s.is_show,s.preprice")
			->alias("s")
			->join("tp_cartype t","t.tid=s.tid")
			->join("tp_cate c","t.cid=c.id")
			->join("tp_brand br","br.bid=c.bid")
			->join("tp_level l","t.lid=l.lid")
			->join("tp_area a",'a.id=s.aid')
			->join("tp_area b",'a.fid=b.id')
			->order(['s.pubtime'])
			->where($condition)
			->paginate([
				'list_rows'=>10,
				'query'=>input('param.'),
			]);
		$this->assign('info',$info);
		return $this->fetch();
	}

	/**
	 * 车源管理--添加
	 */
	public function carsourceadd(){
		if($this->request->isPost()){
			if($this->request->file('image')){
				$file = request()->file('image');
				$info = $file->move('./static/admin/car/carsource/');
				$im[] = "/static/admin/car/carsource/".$info->getSaveName();

				return json_encode(['im'=>$im]);
			}
			if(input('tid') == null){
				foreach (input('img') as $v) {
					if(is_file(".".$v)){
						unlink(".".$v);
					}
				}
				return $this->error('请选择车型车系');
			}
			Db::startTrans();
    		try{
				foreach(input('img') as $v){
					$mid[] = db("sourceimg")->insertGetId(['img'=>$v]);
				}
				$mmid = implode(',',$mid);
				$re = model("Carsource")->insertGetId([
					'tid'		  => input('post.tid'),
					'preprice'	  => input('post.preprice'),
					'distance'	  => input('post.distance'),
					'licensetime' => strtotime(input('post.licensetime')),
					'insurance'	  => strtotime(input('post.insurance')),
					'cktime'	  => strtotime(input('post.cktime')),
					'desc'		  => input('post.desc'),
					'ophone'	  => input('post.ophone'),
					'oname'		  => input('post.oname'),
					'aid'		  => input('post.aid'),
					'pubtime'	  => time(),
					'mid'		  => $mmid,
				]);
				if(!$re){
					throw new Exception("添加失败",2);
				}
				$a = true;
				foreach (input('config') as $k => $v) {
					if(is_array($v)){
						$val = implode(',',$v);
						$res = db('configuration')->insert(['sid'=>$re,'cid'=>$k,'val'=>$val]);
					}else{
						$res = db('configuration')->insert(['sid'=>$re,'cid'=>$k,'val'=>$v]);
					}
					if(!$res){
						$a  = false;
					}
				}
				if($a == false){
					throw new Exception("添加失败",2);
				}
				//提交事务
    			Db::commit();
    			throw new Exception("添加成功",1);
			}catch (\Exception $e){
    			Db::rollback();
    			if($e->getCode()===1){
    				return $this->success($e->getMessage());
    			}else{
    				return $this->error($e->getMessage());
    			}
    		}
		}else{
			//地区
			$area = db('area')->where('level',1)->order(['first'])->select();
			if(input("get.pid") != null){
				$area2 = db('area')->where('fid',input("get.pid"))->order(['first'])->select();
				return $area2;
			}else{
				$area2 = db('area')->where('fid',$area[0]['id'])->order(['first'])->select();
			}
			//品牌
			$brand = model('Brand')->order(['first'])->select();
			if(input("get.bid") != null){

				$c['cate'] = model('cate')->where('bid',input("get.bid"))->select();
				$num = model('cate')->where('bid',input("get.bid"))->count();
				$c['gname'] = model('cate')->field('gname')->distinct ( true )->where('bid',input("get.bid"))->select();
				if($num>0){
					$c['type'] = model("Cartype")->where('cid',$c['cate'][0]['id'])->select();
				}else{
					$c['type'] = [];
				}
				
				return $c;
			}
			if(input("get.cid") != null){
				$cartype = model('cartype')->where('cid',input("get.cid"))->select();
				return $cartype;
			}
			$config = model('Carconfig')->select();
			$this->assign('config',$config);
			$this->assign('brand',$brand);
			$this->assign('area',$area);
			$this->assign('area2',$area2);
			return $this->fetch();	
		}
	}

	/**
	 * 车源管理--修改
	 */
	public function carsourceedit(){
		$re = model('Carsource')->where('sid',input('sid'))->select();
		if($this->request->isPost()){

			if($this->request->file('image')){
				$file = request()->file('image');
				$info = $file->move('./static/admin/car/carsource/');
				$im[] = "/static/admin/car/carsource/".$info->getSaveName();

				return json_encode(['im'=>$im]);
			}
			if(input('tid') == null){
				foreach (input('img') as $v) {
					if(is_file(".".$v)){
						unlink(".".$v);
					}
				}
				return $this->error('请选择车型车系');
			}
			Db::startTrans();
    		try{
    			$im = db("sourceimg")->field('img')->where('mid',"in",$re[0]['mid'])->select();
    			if(input('img')==null){
    				return ;
    			}
    			if(in_array($im[0]['img'], input('img'))){
    				$mmid = $re[0]['mid'];
    			}else{
    				foreach ($im as $v) {
    					if(is_file(".".$v['img'])){
    						unlink(".".$v['img']);
    					}
    				}
    				$im = db("sourceimg")->field('img')->where('mid',"in",$re[0]['mid'])->delete();
    				foreach(input('img') as $v){
						$mid[] = db("sourceimg")->insertGetId(['img'=>$v]);
					}
					$mmid = implode(',',$mid);
    			}
				
				$re = model("Carsource")->where('sid',input("post.sid"))->update([
					'tid'		  => input('post.tid'),
					'preprice'	  => input('post.preprice'),
					'distance'	  => input('post.distance'),
					'licensetime' => strtotime(input('post.licensetime')),
					'insurance'	  => strtotime(input('post.insurance')),
					'cktime'	  => strtotime(input('post.cktime')),
					'desc'		  => input('post.desc'),
					'ophone'	  => input('post.ophone'),
					'oname'		  => input('post.oname'),
					'aid'		  => input('post.aid'),
					'pubtime'	  => time(),
					'mid'		  => $mmid,
				]);
				if(!$re){
					throw new Exception("修改失败",2);
				}
				$a = true;
				db('configuration')->where("sid",input('sid'))->delete();
				foreach (input('config') as $k => $v) {
					if(is_array($v)){
						$val = implode(',',$v);
						$res = db('configuration')->insert(['sid'=>input("post.sid"),'cid'=>$k,'val'=>$val]);
					}else{
						$res = db('configuration')->insert(['sid'=>input("post.sid"),'cid'=>$k,'val'=>$v]);
					}
					if(!$res){
						$a  = false;
					}
				}
				if($a == false){
					throw new Exception("修改失败",2);
				}
				//提交事务
    			Db::commit();
    			throw new Exception("修改成功",1);
			}catch (\Exception $e){
    			Db::rollback();
    			if($e->getCode()===1){
    				return $this->success($e->getMessage());
    			}else{
    				return $this->error($e->getMessage());
    			}
    		}

		}else{
			
			$img = db("sourceimg")->where('mid',"in",$re[0]['mid'])->select();
			//地区
			$area = db('area')->where('level',1)->order(['first'])->select();
			if(input("get.pid") != null){
				$area2 = db('area')->where('fid',input("get.pid"))->order(['first'])->select();
				return $area2;
			}else{
				$a = db('area')->where('id',$re[0]['aid'])->select();
				$area2 = db('area')->where('fid',$a[0]['fid'])->order(['first'])->select();
			}
			//品牌
			$brand = model('Brand')->order(['first'])->select();
			if(input("get.bid") != null){
				$c['cate'] = model('cate')->where('bid',input("get.bid"))->select();
				$num = model('cate')->where('bid',input("get.bid"))->count();
				$c['gname'] = model('cate')->field('gname')->distinct ( true )->where('bid',input("get.bid"))->select();
				if($num > 0){
					$c['type'] = model("Cartype")->where('cid',$c['cate'][0]['id'])->select();
				}else{
					$c['type'] = [];
				}
				
				return $c;
			}else{
				$ca = model('cate')->alias('c')->join("tp_cartype t","t.cid=c.id")->where('tid',$re[0]['tid'])->select();
				$c['cate'] = model('cate')->where('bid',$ca[0]['bid'])->select();
				$c['gname'] = model('cate')->field('gname')->distinct ( true )->where('bid',$ca[0]['bid'])->select();
				if($c['cate']){
					$c['type'] = model("Cartype")->where('cid',$c['cate'][0]['id'])->select();
				}else{
					$c['type'] = [];
				}
			}
			if(input("get.cid") != null){
				$cartype = model('cartype')->where('cid',input("get.cid"))->select();
				return $cartype;
			}
			$configure = db("configuration")->where('sid',input('sid'))->select();
			$config = model('Carconfig')->select();
			$this->assign($c);
			$this->assign('img',$img);
			$this->assign('configure',$configure);
			$this->assign('info',$re);
			$this->assign('config',$config);
			$this->assign('brand',$brand);
			$this->assign('area',$area);
			$this->assign('area2',$area2);
			return $this->fetch();
		}
	}

	/**
	 * 车源管理--删除
	 */
	public function carsourcedel(){
		$id=input('post.id');
		if(!empty(input('post.allid'))){
    		$id=substr(input('post.allid'),0,-1);
    	}
    	Db::startTrans();
    	try{
    		$img = model("Carsource")->field("mid")->where('sid',"in",$id)->select();
    		foreach ($img as $v) {
    			$re = db("sourceimg")->field("img")->where("mid","in",$v['mid'])->select();
    			foreach ($re as $i) {
    				if(is_file(".".$i['img'])){
    					unlink(".".$i['img']);
    				}
    			}
    			$res = db("sourceimg")->field("img")->where("mid","in",$v['mid'])->delete();
    			if($res == 0){

    				throw new Exception("删除失败",2);
    			}
    		}
    		$are = db("configuration")->where("sid","in",$id)->delete();
    		$fin = model("Carsource")->where('sid',"in",$id)->delete();
    		if($fin == 0){
    			throw new Exception("删除失败",2);
    		}
    		Db::commit();
    		throw new Exception("删除成功",1);
		}catch (\Exception $e){
			Db::rollback();
			if($e->getCode()===1){
				return $this->success($e->getMessage());
			}else{
				return $this->error($e->getMessage());
			}
		}
	}
}